package org.zjt.akka;

import akka.actor.ActorRef;
import akka.actor.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * Description: 异常处理、request 、response 处理
 *
 * @author juntao.zhang
 * Date: 2018-06-26 下午9:54
 * @see
 */
@Slf4j
public class ExceptionHandleTest {

    static class SupervisingActor extends AbstractActor {

        ActorRef child = getContext().actorOf(Props.create(SupervisedActor.class), "supervised-actor");

        @Override
        public Receive createReceive() {
            return receiveBuilder().matchEquals("failChild", f ->

                    // 为子节点发送信息
                    child.tell("fail", getSelf()))
                    .matchEquals("zhang",f -> log.info("response msg :{}",f)).build();
        }
    }

    static class SupervisedActor extends AbstractActor {

        @Override
        public void preStart() {
            log.info("supervised actor started");
        }

        @Override
        public void postStop() {
            log.info("supervised actor stopped");
        }

        @Override
        public Receive createReceive() {
            return receiveBuilder().matchEquals("fail", f -> {

                // response 回复 父节点信息
                getSender().tell("zhang",getSelf());

                        log.info("supervised actor fails now");
                        throw new Exception("I failed!");
            }).build();
        }
    }


    ActorSystem system ;

    @Before
    public void startup() {
        system = ActorSystem.create("testSystem");
    }

    /**
     * 相互传话逻辑
     */
    @Test
    public void method1() {
        ActorRef supervisingActor = system.actorOf(Props.create(SupervisingActor.class), "supervising-actor");
        supervisingActor.tell("failChild", ActorRef.noSender());
    }



    @After
    public void shutdown() throws InterruptedException {
        TimeUnit.SECONDS.sleep(20);
        system.terminate();
    }
}
